<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <link rel="stylesheet" href="/stylesheets/side-menu.css">
    <script src="https://js.chargebee.com/v2/chargebee.js"></script>
    <script src="/javascripts/sigma/sigma.min.js"></script>
    <script src="/javascripts/sigma/plugins/sigma.parsers.json.min.js"></script>
    <script src="/javascripts/sigma/plugins/sigma.layout.forceAtlas2.js"></script>
    <script src="/javascripts/sigma/plugins/sigma.plugins.animate.min.js"></script>
    <script src="/javascripts/jquery.min.js"></script>
    <% include statsheader %>
</head>
<body>

<% include statsabove %>

<div id="layout">
    <!-- Menu toggle -->
    <a href="#menu" id="menuLink" class="menu-link">
        <!-- Hamburger icon -->
        <span></span>
    </a>

    <%- include('components/common/menu') %>

    <div id="content">
          <div id="welcomemessage" style="background: white;">
              <p class="large-caption">Please, create a patron account below to start using InfraNodus.</p>
                <p class="medium-caption">This <a href="https://github.com/noduslabs/infranodus">open-source tool</a> and the associated <a href="https://noduslabs.com/category/research/">research</a> are developed solely on the monthly €5 contribution provided by our patrons. We believe this is a working model for crowd-funded R&D and we thank you for your support! You can cancel at any time and we offer a 14-day money back guarantee.</p>

              <% include messages %>

              <div class="warning" id="errors"></div>

                <form action='/signup' id="registration_form" method='post' class="pure-form pure-form-stacked">


                    <p>
                        <input type='text' name='username' id="username" placeholder='username' />
                    </p>
                    <p>
                        <input type='password' name='password' placeholder='password' />
                    </p>
                    <p>
                        <input type='email' name='email' placeholder='email' />
                    </p>
                    <% if (invitation) { %>
                    <p>
                        <input type='text' name='invite' id='invitation' placeholder='invitation code' value=<%=invitation%> />
                    </p>
                    <% } else { %>
                        <input type='hidden' name='invite' id='invitation'/>
                    <% } %>
                    <p>

                      <div class="small-caption">
                      do you accept our <a href="https://infranodus.com/infranodus/privacypolicy?maxnodes=90" target="_blank">privacy policy</a> and our <a href="https://infranodus.com/legal/terms" target="_blank">terms of use</a> and do you consent to receive updates from us<br>

                      </div>
                      <input type='checkbox' name='consent' value='yes'/>

                    </p>
                    <p>
                        <button type='submit' id='register' class="pure-button pure-button-primary">create account</button>
                    </p>
                </form>
                <br>
                <div id="message" class="small-caption"></div>
                <!-- <p class="medium-caption">Patrons get access to the insight generation mode, can request the new features, and have a dedicated  developer on standby to help with a project or provide support. </p> -->
<br>&nbsp;<br>

          </div>
          <div id="graph-container" style="background: white;"></div>

    </div>

</div>

<script src="/javascripts/ui.js"></script>


<script>
;(function(){

    var jsonpath = '/files/signup.json';




// Add a method to the graph model that returns an
// object with every neighbors of a node inside:

    sigma.classes.graph.addMethod('neighbors', function(nodeId) {
        var k,
                neighbors = {},
                index = this.allNeighborsIndex[nodeId] || {};

        for (k in index)
            neighbors[k] = this.nodesIndex[k];

        return neighbors;
    });

// Initialize JSON parser for SIGMA visualization

    sigma.parsers.json(
            jsonpath,
            {
                container: 'graph-container',
                renderer: {
                    container: document.getElementById('graph-container'),
                    type: 'canvas'
                },
                settings: {
                    minNodeSize: 1,
                    maxNodeSize: 13,
                    minEdgeSize: 0.5,
                    maxEdgeSize: 2,
                    labelThreshold: 21
                }
            },
            function(sigma) {

                var i,
                        timeout = 4000,
                        nodes = sigma.graph.nodes(),
                        color_context = '#888',
                        color_addcontext = '#666688',
                        len = nodes.length;


                // This is a fix for JSON
                // Sigma requires that nodes have X, Y, Size and Color properties which our JSON doesn't have. So we add them.
                // We also make the initial graph layout circular, so that ForceAtlas always looks the same

                for (i = 0; i < len; i++) {
                    var angle = Math.PI * 2 * i / len;
                    nodes[i].x = Math.cos(angle);
                    nodes[i].y = Math.sin(angle);
                    nodes[i].size = sigma.graph.degree(nodes[i].id);
                    nodes[i].color = color_context;
                }


                // Do ForceAtlasLayout

                sigma.startForceAtlas2();

                // Don't run it forever not to overheat :)

                setTimeout(function() {
                    sigma.stopForceAtlas2();
                },timeout);




                // Zoom Graph Control

                var c = sigma.camera;


                $("#zoom-in").on('click', function(e) {
                    // Zoom in - single frame :
                    c.goTo({
                        ratio: c.ratio / c.settings('zoomingRatio')
                    });
                });

                $("#zoom-out").on('click', function(e) {
                    // Zoom out - single frame :
                    c.goTo({
                        ratio: c.ratio * c.settings('zoomingRatio')
                    });
                });




            }
    );


    $(document).ready(function(){
    function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

    var redirect = getUrlVars()["redirect"];

    var login = getUrlVars()["login"];

    $('#redirect').val(redirect);

    $('#username').val(login);


    });


    function isMobileDevice() {
      return (typeof window.orientation !== "undefined") || (navigator.userAgent.indexOf('IEMobile') !== -1);
    };

    console.log();

    document.addEventListener("DOMContentLoaded", function() {

        var cbInstance = window.Chargebee.init({site: "infranodus", enableGATracking: true, enableFBQTracking: true});

        var account_created;

        var popupBlocked = 0;

        if (isMobileDevice()) {
          popupBlocked = 1;
        }


        $("#register").click(function(event){


          // That will only happen if we retriggered the click
          if (popupBlocked == 1) {

            var payPage = window.open('',"_blank");
            payPage.document.write('Loading the subscription module...');

          }


          event.preventDefault();

          $('#register').prop('disabled', true);
          $('#message').html("We are now forwarding you to our payment processor... If the window doesn't open, please, <a href='javascript:void' id='reactivate'>click here to open the payment page</a>...");
          $("#reactivate").click(function() {
                popupBlocked = 1;
                $('#register').click();
          });

          $.post('/signup', $("#registration_form").serialize())
                  .done(function(res) {
                      if (res.errormsg) {
                        $('#errors').html(res.errormsg);
                        $('#message').html('');
                        $('#register').prop('disabled', false);
                        if (payPage) {
                          payPage.close();
                        }
                      }
                      else if (res.moveon) {
                        if (payPage) {
                          payPage.close();
                        }
                        window.location.href = res.moveon;
                      }
                      else {
                        $('#errors').html('');

                        cbInstance.openCheckout({
                          hostedPage: function() {
                            // Hit your end point that returns hosted page object as response
                            // This sample end point will call checkout new api
                            // https://apidocs.chargebee.com/docs/api/hosted_pages#checkout_new_subscription
                            // If you want to use paypal, go cardless and plaid, pass embed parameter as false
                            return new Promise(function(resolve, reject){
                               var obtainedResponse = res.hosted_page;
                               if (popupBlocked == 1) {
                                 payPage.location.href = obtainedResponse['url'];
                               }
                               resolve(obtainedResponse);

                            });
                            },
                            loaded: function() {
                              $('#errors').html('Processing payment...');
                              console.log("checkout opened");
                              if(window.parent.ga) {
                                   console.log('GA detected');
                                   ga('send', {
                                       hitType: 'event',
                                       eventCategory: 'InfraNodus',
                                       eventAction: 'checkout_opened'
                                   });
                               }
                            },
                            error: function() {
                              if (popupBlocked == 1) {
                                $('#errors').html('The payment link was opened in a new window. If something went wrong, you can try submitting the details again.');
                                $('#message').html('');
                                $('#register').prop('disabled', false);
                              }
                              else {
                                console.log("error");
                                $('#errors').html('There was an error with the sign up process. Please, try again and if it doesn\'t work, <a href="http://noduslabs.com/contact/"">contact us</a>, so we can sort this out for you. Thanks!');
                                $('#message').html('');
                                $('#register').prop('disabled', false);
                                if (payPage) {
                                  payPage.close();
                                }
                              }
                            },
                            close: function() {
                              // console.log("checkout closed");
                              if (account_created == 'success') {
                                window.location.href = '/login?login=' + $('#username').val();
                                // $('#errors').html('It appears like the checkout process ended abruptly. Your account appears to have been created, so, please, <a href="/login?login=' + $('#username').val() + '">try to log in using your details</a>.');
                                // $('#message').html('');
                                // $('#register').prop('disabled', false);
                              }
                              else {
                                $('#errors').html('It appears like the checkout process ended abruptly. Your account may have not been created. Please, try to submit this form again using the same details.');
                                $('#message').html('');
                                $('#register').prop('disabled', false);
                              }
                            },
                            success: function(hostedPageId) {
                              account_created = 'success';
                              // console.log("checkout success");
                              // console.log($("#registration_form").serialize());
                              // console.log(hostedPageId);
                            //  console.log(hostedPageId);
                               // Hosted page id will be unique token for the checkout that happened
                               // You can pass this hosted page id to your backend
                               // and then call our retrieve hosted page api to get subscription details
                               $.post('/signup', $("#registration_form").serialize() + '&hostedPage=' + hostedPageId)
                                       .done(function(res) {

                                         if(window.parent.ga) {
                                              ga('send', {
                                                  hitType: 'event',
                                                  eventCategory: 'InfraNodus',
                                                  eventAction: 'Subscribed'
                                              });
                                          }
                                          if (res.moveon) {
                                            if (payPage) {
                                              payPage.close();
                                            }
                                            window.location.href = res.moveon;
                                          }
                                       })
                                       .fail(function(res) {
                                          $('#errors').html('Account not created as something went wrong...');
                                           console.log(res);
                                       });
                            },
                            step: function(value) {
                              // if (value == 'thankyou_screen') {
                              //
                              //   if (payPage) {
                              //     payPage.close();
                              //   }
                              //   window.location.href = '/login?login=' + $('#username').val();
                              //
                              // }
                              // value -> which step in checkout
                          //    $('#errors').html(value);
                              console.log(value);
                              if(window.parent.ga) {
                                   ga('send', {
                                       hitType: 'event',
                                       eventCategory: 'InfraNodus',
                                       eventAction: value
                                   });
                               }
                            }
                          });

                      }

                  })
                  .fail(function(res) {
                      console.log(res);
                      if (payPage) {
                        payPage.close();
                      }
                  });




          });



    });




})();


</script>

<% include statsbelow %>

</body>
</html>
